<template>
  <div class="search-container">
    <form action="/">
      <van-search v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isSearchResult = false" />
    </form>
    <!-- 搜索结果 -->
    <SearchResult v-if="isSearchResult"
      :search-text="searchText"></SearchResult>
    <!-- 搜索联想建议 -->
    <SearchSuggest v-else-if="searchText"
      :search-text="searchText"
      @faSearch="onSearch"></SearchSuggest>
    <!-- 搜索历史记录 -->
    <SearchHistory v-else
      :search-histories="searchHistories"
      @deleteAllHistories="searchHistories=[]"
      @search="onSearch"></SearchHistory>
  </div>
</template>

<script>
import SearchSuggest from './components/SearchSuggest'
import SearchResult from './components/SearchResult'
import SearchHistory from './components/SearchHistory'

import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    SearchSuggest,
    SearchResult,
    SearchHistory
  },
  data () {
    return {
      searchText: '',
      isSearchResult: false,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORY') || []
    }
  },

  watch: {
    searchHistories: {
      handler (val) {
        // console.log(val)
        setItem('TOUTIAO_SEARCH_HISTORY', val)
      }
    }
  },
  methods: {
    onSearch (val) { // 既接收子组件传过来的联想搜索内容 也接收搜索框本身回车后的内容
      // console.log(val)
      // console.log(typeof val)
      if (typeof val !== 'string' || val.trim().length === 0) return
      this.searchText = val
      // 获取到输入框内容后 按下回车要存储到历史记录组件中 但是不能重复添加
      const index = this.searchHistories.indexOf(val)
      // console.log(index)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // 设置历史记录储存的数据 最多5条 超出后覆盖
      if (this.searchHistories.length > 5) this.searchHistories.length = 5

      this.isSearchResult = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  .van-search {
    background-color: #2892ff;
    .van-search__action {
      color: #fff;
    }
  }
}
</style>
